@extends('layouts.app')

@section('title', '卡券管理')

@section('css-import')
<style type="text/css">
.form-input-control{
	margin-bottom: 20px;
}
.page-s{
	float:right;
	display: inline-block;
	padding-bottom: 0px;
	margin: 29px 9px;
	border-radius: 4px;
}
.loadCardBackground{
	width: 350px;
	display: block;
	margin:15px;
}
.card-list,.card-relist{
	margin-top:10px;
	cursor:move;
}
.box{
	text-align: center;
	overflow: hidden;
	position: relative;
	height: 12em;
}
.box:before{
	content: "";
	width: 0;
	height: 100%;
	background: #000;
	padding: 14px 18px;
	position: absolute;
	top: 0;
	left: 50%;
	border-radius: 3%;
	/*opacity: 0;*/
	width: 100%;
	left: 0;
	opacity: 0.5;
	transition: all 500ms cubic-bezier(0.47, 0, 0.745, 0.715) 0s;
}

.box img{
	width: 100%;
	height: auto;
}
.box .box-content{
	width: 100%;
    padding: 0px 18px; 
    color: #fff;
    position: absolute;
    top: 22%;
    left: 0;
}
.box .title{
	font-size: 22px;
	font-weight: 600;
	line-height: 30px;
	text-transform: uppercase;
	margin: 0;
	transition: all 0.5s ease 0s;
	transition-delay: 0.7s;
}
.box .post{
	font-size: 14px;
	text-transform: capitalize;
	transition: all 0.5s ease 0s;
	transition-delay: 0.7s;
}

.box .icon{
	padding: 0;
	margin: 0;
	list-style: none;
	margin-top: 15px;
}
.box .icon li{
	display: inline-block;
}
.box .icon li a{
	display: block;
	width: 40px;
	height: 40px;
	line-height: 40px;
	border-radius: 50%;
	background: #f74e55;
	font-size: 1.9rem;
	font-weight: 700;
	color: #fff;
	margin-right: 5px;
}

@media screen and (max-width: 1440px){
	.box .title {
		font-size: 15px;
	}
	.box .post {
    	font-size: 10px;
	}
	.box .icon {
		margin-top: 6px;
	}
	.box .icon li a {
		width: 30px;
    	height: 30px;
    	font-size: 10px;
    	line-height: 34px;
	}
	.box .box-content {
		top: 11%;
	}
}
.monochrome{
	-webkit-filter: grayscale(80%); 
    -moz-filter: grayscale(80%); 
    -ms-filter: grayscale(80%); 
    -o-filter: grayscale(80%); 
    filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);  
    _filter:none; 
}
.card-list:hover .monochrome{
	-webkit-filter: grayscale(0%); 
    -moz-filter: grayscale(0%); 
    -ms-filter: grayscale(0%); 
    -o-filter: grayscale(0%); 
    filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=0);  
    _filter:none; 
    -webkit-transition: filter .5s; 
    -moz-transition: filter .5s; 
    -ms-transition: filter .5s; 
    -o-transition: filter .5s; 
    transition: filter .5s;

}

.card-list:hover .box:before{
	-webkit-transition: filter .5s; 
    -moz-transition: filter .5s; 
    -ms-transition: filter .5s; 
    -o-transition: filter .5s; 
    transition: filter .5s;
	opacity: 0;
}

#l-map{height:300px;width:100%;}
#r-result{width:100%;}

.modal-backdrop{
	z-index: -1 !important;
}

</style>
@endsection

@section('content-fluid')
<div class="row">
	<!-- BASIC TABLE -->
	
	<div class="panel">
		<div class="panel-heading">
			<h3 class="panel-title">卡券管理</h3>
		</div>
		<div class="panel-body">
			<ul class="nav nav-pills" style="float:left;">
			  <li role="presentation" class="orderall">
			  	<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
			      {{isset($_GET['province'])?$_GET['province']:"省份"}} <span class="caret"></span>
			    </a>
			    <ul class="dropdown-menu">
			      <li role="presentation" class="shijiazhuang"><a href="/manageCoupon">所有省份</a></li>
			      @foreach($provinces as $v)
			      <li role="presentation" class="shijiazhuang"><a href="?province={{$v}}">{{$v}}</a></li>
			      @endforeach
			    </ul>
			  </li>
			</ul>
			<ul class="nav nav-pills" style="float:left;">
			  <li role="presentation" class="orderall">
			  	<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
			      {{isset($_GET['city'])?$_GET['city']:"城市"}} <span class="caret"></span>
			    </a>
			    <ul class="dropdown-menu">
			      <li role="presentation" class="shijiazhuang"><a href="/manageCoupon">所有城市</a></li>
			      @foreach($citys as $v)
			      <li role="presentation" class="shijiazhuang"><a href="?city={{$v}}">{{$v}}</a></li>
			      @endforeach
			    </ul>
			  </li>
			</ul>
			<form action="/manageCoupon" method="get">
				<div class="input-group col-md-4 pull-right" style="z-index: auto;">
					<input type="text" value="{{$_GET['shop_name'] ?? ''}}" class="form-control app-search-text" name="shop_name" AUTOCOMPLETE="off" placeholder="搜索商户名">
					<span class="input-group-btn"><button type="submit" class="btn btn-primary search-jslx"><i class="fa fa-search"></i></button></span>
				</div>
			</form>
			@if($coupons->count()>0)
		    <table class="table table-hover">
				<thead>
					<tr>
						<th>#</th>
						<th>卡券名</th>
						<th>商户名</th>
						<th>库存</th>
						<th>定价</th>
						<th>在售状态</th>
						<th>省份城市</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
			
					@foreach($coupons as $k=>$v)
					<tr>
						<td>{{$v->id}}</td>
						<td>{{$v->coupon_name}}</td>
						<td>{{$v->shop_name ?? '未填写'}}</td>
						<td>{{$v->num}}</td>
						<td>{{$v->price}} 元</td>
						<td>{{$v->valid==0?"下架":"在售"}}</td>
						<td>{{$v->province}}{{$v->city}}</td>
						<td><a href="###" data-toggle="modal" data-target="#exampleModal" data-couponid="{{$v->id}}"><i class="fa fa-info-circle"></i> 编辑</a>
							<a href="###" class="del-coupon" data-couponid="{{$v->id}}"><i class="fa fa-trash"></i> 删除</a>
						</td>
					</tr>
					@endforeach
				</tbody>
			</table>
			{{ $coupons->appends(['starttime' => $_GET['starttime']??'','endtime'=>$_GET['endtime']??'','pay'=>$_GET['pay']??''])->links() }} 
			<div class="page-s">本页共{{ $coupons->count() }}条</div>
			<div class="page-s">共{{ $coupons->total() }}条</div>
			<div class="page-s">当前第{{ $coupons->currentPage() }}页</div>
			<div class="page-s">共{{ $coupons->lastPage() }}页</div>
			@endif

		</div>
	</div>
	<!-- END BASIC TABLE -->
	
	
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" style="z-index:auto">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">修改卡券信息</h4>
      </div>
      <form action="/coupon/edit" method="post" enctype="multipart/form-data" id="EditCardInfoForm">
      <div class="modal-body">
          <div class="form-group">
            <label class="control-label">标题名称</label>
			<input type="text" name="coupon_name" value="" class="form-control form-input-control" placeholder="标题名称" alt="标题名称">
			
			<label class="control-label">优惠开始时间</label>
			<input type="date" name="starttime" class="form-control form-input-control" alt="开始可用时间 年-月-日">
			
			<label class="control-label">优惠结束时间</label>
			<input type="date" name="stoptime" class="form-control form-input-control" alt="结束可用时间 年-月-日">
			
			<label class="control-label">发布数量</label>
			<input type="number" name="num" value="1" class="form-control form-input-control" placeholder="每日可用次数" alt="每日可用次数">

			<label class="control-label">定位地址</label>
			<div id="l-map"></div>
			<input type="text" id="suggestId" name="address" AUTOCOMPLETE="off" value="" class="form-control limit_days form-input-control" alt="详细地址" placeholder="详细地址">
			<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
			
			<label class="control-label">售价</label>
			<input type="text" name="price" value="" class="form-control form-input-control" placeholder="卡券出售价格" alt="卡券出售价格">

			<label class="control-label">成本价</label>
			<input type="text" name="cost_price" value="" class="form-control form-input-control" placeholder="卡券成本价格" alt="卡券成。本价格">

			<label class="control-label">活动介绍</label>
			<div id="div3" placeholder="介绍卡券特权优惠" alt="介绍卡券特权优惠"></div>
			<input type="hidden" name="desc" id="desc" onchange="descChange(this)" value="">

			<label class="control-label">封面图片</label>
			<img src="" class="loadCardBackground">
			<input type="file" name="mealcardBackground" class="form-input-control" alt="背景图">

			<label class="control-label">购卡优惠</label>
			<select class="form-control" name="benefit">
				<option value="-1">没有优惠</option>
				<option value="0">购任意卡优惠</option>
				<option value="1">198套餐优惠</option>
				<option value="2">398套餐优惠</option>
			</select>
			<br>
			<label class="control-label">是否在售</label>
			<div class="switch form-input-control" data-on-label="在售" data-off-label="下架">
			    <input type="checkbox" name="cardstatus_state" value="" />
			    <input type="hidden" name="cardstatus" value="">
			</div>
          </div>
          <input type="hidden" name="coupon_id" value="">
          <input type="hidden" name="lng" value="">
		  <input type="hidden" name="lat" value="">
		  <input type="hidden" name="province" value="">
		  <input type="hidden" name="city" value="">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="submit" class="btn btn-primary confirmeditCard" >修改设置</button>
      </div>
      </form>
    </div>
  </div>
</div>
@endsection

@section('js-import')
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=vQBEj1uCOLD3MPMwoxrICDUhz7vhyR0e"></script>
<script type="text/javascript" src="https://unpkg.com/wangeditor@3.1.1/release/wangEditor.min.js"></script>
@endsection

@section('js-write')
<script type="text/javascript">
	var delcoupon = function(){
		var couponid = $(this).attr('data-couponid');
		swal({
		  title: '确定删除该卡券吗', 
		  text: '删除后将无法恢复！', 
		  type: 'question',
		  showCancelButton: true, 
		  confirmButtonColor: '#3085d6',
		  cancelButtonColor: '#d33',
		  confirmButtonText: '确定', 
		  cancelButtonText: '取消',
		  confirmButtonClass: 'btn btn-success',
		  cancelButtonClass: 'btn btn-danger',
		  buttonsStyling: true
		}).then(function(al) {
			if(al.value){
				$.ajaxSetup({
				    headers: {
				        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
				    }
				});
				$.post('/coupon/item/del',{'couponid':couponid},function(response){
					if(response.success){
						setTimeout(function(){
				            location.href = '/manageCoupon';
				        },2000);
						toastr.success(response.message);
					}else{
						toastr.error(response.message);
					}
				});
			}
		});
	};
	
	$('.del-coupon').click(delcoupon);
	// 百度地图API功能
	function G(id) {
		return document.getElementById(id);
	}

	var map = new BMap.Map("l-map");
	map.addControl(new BMap.NavigationControl());
	map.enableScrollWheelZoom(true);
	map.centerAndZoom("石家庄",12); // 初始化地图,设置城市和地图级别。
	function addbj(lng_,lat_){
		var point = new BMap.Point(lng_,lat_);  // 创建点坐标
		map.centerAndZoom(point,18); // 初始化地图,设置城市和地图级别。
		var marker = new BMap.Marker(point)
		marker.enableDragging();
		map.addOverlay(marker);    //添加标注

	}
	
	var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
			{"input" : "suggestId"
			,"location" : map
		});

	ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
	var str = "";
		var _value = e.fromitem.value;
		var value = "";
		if (e.fromitem.index > -1) {
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}    
		str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
		
		value = "";
		if (e.toitem.index > -1) {
			_value = e.toitem.value;
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}    
		str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
		G("searchResultPanel").innerHTML = str;
	});

	var myValue;
	ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
	var _value = e.item.value;
		myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
		
		setPlace();
	});

	function setPlace(){
		map.clearOverlays();    //清除地图上所有覆盖物
		function myFun(){
			var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
			var gc = new BMap.Geocoder();
            var pointAdd = new BMap.Point(pp.lng, pp.lat);
            gc.getLocation(pointAdd, function(rs){
                //或者其他信息
                $('input[name="province"]').val(rs.addressComponents.province);
                $('input[name="city"]').val(rs.addressComponents.city);
            })
			setlnglat(pp.lng,pp.lat)
			map.centerAndZoom(pp, 18);
			var marker = new BMap.Marker(pp)
			marker.enableDragging();    
			marker.addEventListener("dragend", function(e){    
			    setlnglat(e.point.lng,e.point.lat);
			})
			map.addOverlay(marker);    //添加标注
		}
		var local = new BMap.LocalSearch(map, { //智能搜索
		  onSearchComplete: myFun
		});
		local.search(myValue);
	}

	function setlnglat(lng,lat){
		$('input[name="lng"]').val(lng);
		$('input[name="lat"]').val(lat);
	}

	var E = window.wangEditor
	var editor = new E('#div3')
	editor.customConfig.uploadImgServer = '/coupon/upload'  // 上传图片到服务器
	editor.customConfig.uploadImgHeaders = {
	    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
	};
	editor.customConfig.uploadFileName = 'images';
	var $text1 = $('#desc');
	editor.customConfig.onchange = function (html) {
        // 监控变化，同步更新到 textarea
        $text1.val(html)
    }
    function descChange(this_){
    	editor.txt.html(document.getElementById("desc").value);
    }
    // 自定义菜单配置
    editor.customConfig.menus = [
        'head',  // 标题
	    'underline',  // 下划线
	    'strikeThrough',  // 删除线
	    'foreColor',  // 文字颜色
	    'backColor',  // 背景颜色
	    'link',  // 插入链接
	    'list',  // 列表
	    'justify',  // 对齐方式
	    'emoticon',  // 表情
	    'image',  // 插入图片
	    'video',  // 插入视频
	    'undo',  // 撤销
	    'redo'  // 重复
    ]
	editor.create()
	
	$('#exampleModal').on('show.bs.modal', function (event) {
	  var button = $(event.relatedTarget) // Button that triggered the modal
	  var couponid = button.data('couponid') // Extract info from data-* attributes
	  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
	  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
	  var modal = $(this);
	  modal.find('.form-input-control').val('');
	  modal.find('.loadCardBackground').attr('src','');
	  modal.find('input[type="text"]').val('');
	  modal.find('input[type="time"]').val('');
	  modal.find('input[type="number"]').val('');
	  $.ajaxSetup({
		    headers: {
		        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
		    }
	  });
	  $.post('/coupon/details',{'coupon_id':couponid},getcardinfo);
	  modal.find('input:radio[name="business_type"]').change(checkedBusiness);
	  modal.find('.groupnum').bind('input propertychange',changeVal);
	});
	// 饭卡业务类型
	var card_type = ['SJ','CK','XS','ZH'];
	var card_type_text = ['跟随时间递减','次数卡','限时卡','组合卡'];
	var subStr= /&&&/ig;
	var card_activity = ['SE','CE'];
	var card_status_de = [0,1];
	function getcardinfo(response){
		console.log(response);
		var coupon = response.data;
		var is_cardstatus_state = coupon.valid==1;
		$("input:checkbox[name='cardstatus_state']")
		.val(Number(is_cardstatus_state));
		$('[name="cardstatus"]').val(card_status_de[Number(is_cardstatus_state)]);

		$("[name='cardstatus_state']").bootstrapSwitch({
			onText:"在售",
			offText:"下架",
			onSwitchChange:function(event,state){
				$("[name='cardstatus_state']").val(Number(state));
				$('[name="cardstatus"]').val(card_status_de[Number(state)]);
			}
		});
		$("[name='cardstatus_state']").bootstrapSwitch('state', is_cardstatus_state);
		$('input[name="coupon_name"]').val(coupon.coupon_name);
		$('input[name="starttime"]').val(coupon.start_time);
		$('input[name="stoptime"]').val(coupon.over_time);
		$('input[name="num"]').val(coupon.num);
		$('input[name="price"]').val(coupon.price);
		$('#desc').val(coupon.coupon_desc);
		$("#desc").change();
		$('.loadCardBackground').attr('src',coupon.cover_img);
		$('input[name="coupon_id"]').val(coupon.id);
		$('input[name="lng"]').val(coupon.lng);
		$('input[name="lat"]').val(coupon.lat);
		$('input[name="province"]').val(coupon.province);
		$('input[name="city"]').val(coupon.city);
		$('input[name="cost_price"]').val(coupon.cost_price);
		
		addbj(coupon.lng,coupon.lat);
		
		$('input[name="address"]').val(coupon.address);
	}

	$('input[type=file][name=mealcardBackground]').change(function(e){
		var files = e.target.files;
		var v = $(this).val();
		var reader = new window.FileReader();
		reader.readAsDataURL(files[0]);
		//异步加载文件成功
	    reader.onload = function(e){
	       // reader.result 表示图片地址
	       $('.loadCardBackground').attr('src',reader.result);
	    }
	});

	function changeVal(){
		var num198 = Number($('input[name="num_198"]').val());
		var num258 = Number($('input[name="num_258"]').val());
		var num298 = Number($('input[name="num_298"]').val());
		$('input[name="frequency"]').val(num198+num258+num298);
	}

	function checkedBusiness(){
		var value = $(this).val();
		if(value=='XS'){
			$('.limitdaynum').removeClass('hide');
			$('.groupcard').hasClass('hide')?'':$('.groupcard').addClass('hide');
		}else if(value=='ZH'){
			$('.groupcard').removeClass('hide');
			$('.limitdaynum').hasClass('hide')?'':$('.limitdaynum').addClass('hide');
		}else{
			$('.limitdaynum').hasClass('hide')?'':$('.limitdaynum').addClass('hide');
			$('.groupcard').hasClass('hide')?'':$('.groupcard').addClass('hide');
		}
	}

	var SendParam = {'dataType':'json'};

	SendParam.beforeSubmit = function(formData, jqForm, options){
	    for (var i = 0; i < formData.length; i++) {
	        var t = $('input[name="'+formData[i].name+'"]').attr('alt');
	        if(formData[i].value==''){
	            if(formData[i].type=='file'||formData[i].type=='checkbox'){
	                continue;
	            }else{
	                var nameV = formData[i].name;
	                if(nameV!='limitday'&&nameV!='num_198'&&nameV!='num_258'&&nameV!='num_298'){
	                    toastr.error('请填写'+t+'！');
	        			console.log(formData[i].name);
	                    return false;
	                }
	                if(nameV=='limitday'&&$('input[name="business_type"]:checked').val()=='XS'){
	                    toastr.error('请填写'+t+'！');
	                    console.log(formData[i].name);
	                    return false;
	                }
	                if($('input[name="business_type"]:checked').val()=='ZH'&&nameV=='num_198'&&nameV=='num_258'&&nameV=='num_298'){
	                    toastr.error('请填写'+t+'！');
	                    console.log(formData[i].name);
	                    return false;
	                }
	            }
	        }
	        
	    }
	};

	SendParam.success = function(response) {
		console.log(response);
		if(response.success){
	        setTimeout(function(){
	            location.href = '/manageCoupon';
	        },2000);
			toastr.success(response.message);
		}else{
			toastr.error('修改失败，请联系开发人员！');
		}
	};

	SendParam.error = function(XMLHttpRequest, textStatus, errorThrown) {
		if(XMLHttpRequest.status==422){
			var RegError = XMLHttpRequest.responseJSON.errors;
			for(var o in RegError){
				for (var i = 0; i < RegError[o].length; i++) {
					toastr.error(RegError[o][i]);
				}
			}
		}
	};

	ajaxForm_('#EditCardInfoForm',SendParam);

</script>
@endsection